﻿using System;
using System.Collections.Generic;
using System.Linq;
using ZSZ.DTO;
using ZSZ.Application.IService;
using ZSZ.Core.Entities;
using ZSZ.EntityFramework;

namespace ZSZ.Application.Service
{
    public class SettingService : Repository<SettingEntity>, ISettingService
    {
        public SettingDTO[] GetAll()
        {
            /*
            return bs.GetAll().Select(s => new SettingDTO
            {
                Id = s.Id,
                CreateDateTime = s.CreateDateTime,
                Name = s.Name,
                Value = s.Value
            }).ToArray();*/
            var list = new List<SettingDTO>();
            foreach (var setting in GetAllDataEntity())
            {
                var dto = new SettingDTO
                {
                    CreateDateTime = setting.CreateDateTime,
                    Id = setting.Id,
                    Name = setting.Name,
                    Value = setting.Value
                };
                list.Add(dto);
            }
            return list.ToArray();
            
        }

        public bool? GetBoolValue(string name)
        {
            string value = GetValue(name);
            if(value==null)
            {
                return null;
            }
            else
            {
                return Convert.ToBoolean(value);
            }
        }

        public int? GetIntValue(string name)
        {
            string value = GetValue(name);
            if (value == null)
            {
                return null;
            }
            else
            {
                return Convert.ToInt32(value);
            }
        }

        public string GetValue(string name)
        {
            var setting = GetAllDataEntity()
                .SingleOrDefault(s => s.Name == name);
            if (setting == null)   //没有
            {
                return null;
            }
            else
            {
                return setting.Value;
            }
        }

        public void SetBoolValue(string name, bool value)
        {
            SetValue(name, value.ToString());
        }

        public void SetIntValue(string name, int value)
        {
            SetValue(name, value.ToString());
        }

        public void SetValue(string name, string value)
        {
           
                var setting = GetAllDataEntity().SingleOrDefault(s => s.Name == name);
                if(setting==null)    //没有，则新增
                {
                    SaveOrUpdate(new SettingEntity { Name=name,Value=value},true);
                }
                else
                {
                    setting.Value = value;
                    SaveOrUpdate(setting,false);
                }
                
            
        }

        public SettingService(ZSZDbContext context) : base(context)
        {
        }
    }
}
